use anyhow::{Context, Result};
use gpgme::{Context, KeyAlgorithm, Protocol};
use std::path::Path;
use tokio::fs;

pub async fn check_gpg_keys(config: &crate::config::Config) -> Result<()> {
    let pub_key_path = &config.storage.gpg_key_path;
    let priv_key_path = &config.storage.gpg_private_key_path;
    
    // 检查公钥和私钥是否存在
    if !pub_key_path.exists() || !priv_key_path.exists() {
        return Err(anyhow::anyhow!(
            "GPG 密钥未找到。请使用脚本生成密钥对: keys/generate_keys.sh"
        ));
    }

    // 验证密钥是否有效
    let mut ctx = Context::from_protocol(Protocol::OpenPgp)?;
    let pub_key_data = fs::read(pub_key_path).await?;
    let keys = ctx.import(&pub_key_data)?;
    
    if keys.imported() == 0 {
        return Err(anyhow::anyhow!("无法导入公钥，可能已损坏"));
    }
    
    log::debug!("GPG 密钥验证成功");
    Ok(())
}

pub async fn sign_release_file(release_path: &Path) -> Result<Vec<u8>> {
    let mut ctx = Context::from_protocol(Protocol::OpenPgp)?;
    ctx.set_armor(true);
    
    // 加载私钥
    let priv_key_path = crate::config::Config::load_or_create("config.toml")
        .await?
        .storage
        .gpg_private_key_path;
    
    let priv_key_data = fs::read(priv_key_path).await?;
    ctx.import(&priv_key_data)?;
    
    // 获取密钥
    let key = ctx.secret_keys()?.next().ok_or_else(|| anyhow::anyhow!("没有可用的签名密钥"))?;
    ctx.add_signer(&key)?;
    
    // 签名文件
    let mut output = Vec::new();
    let data = fs::read(release_path).await?;
    
    ctx.sign_detached(&data, &mut output)?;
    Ok(output)
}